/**
 * 涂鸦主页js
 * 2017年11月19日 星期日
 */
import {
    instance
} from '../../../src/Web'
// 系统全局性变量
window.Web = instance

$(function(){
    var Page = 1,               // 分页
        AllPage,                // 总数据页码
        DataStack = [],         // 数据缓存器
        Option = {}             // 页面数据存储器
        ;

    class Pager{
        constructor(){
            this.DomListener();
            this.loadDataSet();
            this.floatDsActive(true);
        }
        // 时间监听
        DomListener(){
            var instance = this;
            // 写入涂鸦控件
            $('#write_lnk').click(function(){
                instance.progress(false);
                Web.modal('#write_ds');
            });
            // 保存涂鸦
            $('#write_ds_save').click(function(){
                var savedata = Web.formJson('#write_ds form');
                savedata.content = savedata.content.trim();
                if(!savedata.content){
                    var $ctt = $('#inputContent');
                    $ctt.attr('class', 'form-control is-invalid');
                    Web.ModalAlert($('#write_ds form'), '内容必填！');
                    return false;
                }
                var el = $(this);
                instance.progress(true);
                Web.ResetForm('#write_ds form');
                savedata.__args = {feekdata: 1};    // 成功以后反馈数据
                Web.ApiRequest('graffiti/save',savedata,function(rdata){
                    instance.progress(false);
                    var msg = rdata.msg;
                    if(rdata.code == 1){
                        msg = '涂鸦数据写入成功！';
                        instance.arrayRender([rdata.data], 'prepend');
                    }
                    Web.ModalAlert($('#write_ds form'), msg);
                });
            });
            // 内容输入监听器
            $('#inputContent').change(function(){
                var el = $(this);
                var value = el.val().trim();
                if(value){
                    el.attr('class', 'form-control is-valid');
                }
                else{
                    el.attr('class', 'form-control is-invalid');
                }
            });
            // 翻页计算数据，与移动端不懂。绑定时间时无效
            // 数据翻页
            // 滚动到底部，自动翻页
            // 分组页面
            var gLoadSecLimiter = 0; // 加载间隔，方式一次滚动加载许多次
            var GroupHtnmdMk = false;
            $(document).scroll(function(){
                var docH = $(document).height(),
                    winSt = $(window).scrollTop(),                    
                    winH = $(window).height()
                    ;
                if((docH- winSt - winH) <= 10){
                    if(Page >= AllPage){
                        return false;
                    }                
                    if(gLoadSecLimiter != 0){
                        setTimeout(function(){
                            gLoadSecLimiter = 0;
                        },3000);   
                        return false;
                    }    
                    Page += 1;
                    instance.loadDataSet();
                    gLoadSecLimiter = 3;
                }
            });

            // 快捷键
            $(document).keydown(function(e){
                if(e.shiftKey && e.which == 84){    // Shitf + T
                    instance.progress(false);
                    Web.modal('#write_ds');
                }
            });
            // 动态卡时间监听
            // 移动到元素上
            $('#float-ds').mouseover(function(){
                instance.floatDsActive(false);
            });
            // 移除动态浮动框
            $('#float-ds').mouseout(function(){
                instance.floatDsActive(true);
            });
        }
        // 加载数据列表
        loadDataSet(){
            var instance = this;
            Web.ApiRequest('graffiti/get',{page: Page},function(rdata){
                if(rdata.code == 1){
                    var dd = rdata.data;
                    var rs = dd.rs;
                    if(!AllPage || Page == 1){
                        AllPage = Web.getAllPage(dd.count,dd.num);
                    }
                    instance.arrayRender(rs, dd.page == 1);
                }
            });
        }
        /**
         * @param {array} array 
         * @param {bool|string} cover 
         */
        arrayRender(array, cover){
            if('object' == typeof array){
                var html = '';
                for(var i=0; i<array.length; i++){
                    var el = array[i];
                    var idx = DataStack.push(el) - 1;
                    html += '\
                        <li class="list-group-item list-group-item-action flex-column align-items-start" data-no="'+idx+'">    \
                            <div class="d-flex w-100 justify-content-between">\
                                <h5 class="mb-1">'+(el.sign? el.sign:'匿名')+'</h5>\
                                <small>'+el.mtime+'</small>\
                            </div>\
                            <p class="mb-1">'+el.content+'</p>\
                            '+ (el.city? '<small>来自<span class="text-info">'+el.city+'</span></small>': '')+'\
                            <p class="mb-1 text-right"><a href="javascript:;" class="'+(el.star_count? 'text-success':'text-secondary')+' js__star"> \
                                <i class="fa fa-star">'+(el.star_count? el.star_count: '')+'</i></a></p>\
                        </li>\
                    '
                    ;
                }
                // console.log(rdata);
                if(!html){
                    return;
                }
                var $html = $(html);
                // 数据事件绑定 - star
                $html.find('a.js__star').click(function(){
                    var dom = $(this);
                    var eLi = dom.parents('li.list-group-item');
                    if(eLi.length > 0){
                        var idx = eLi.data('no');
                        var dd = DataStack[idx];
                        var savedata = {listid: Base64.encode(dd.listid)};
                        savedata.star_count = dd.star_count? dd.star_count + 1: 1;
                        Web.ApiRequest('graffiti/save',savedata,function(rdata){
                            if(rdata.code == 1){
                                dom.find('i').html(savedata.star_count);
                                dom.attr('class', 'text-success js__star');
                            }
                        });
                    }
                });
                if(cover){
                    if('prepend' === cover){
                        $('#js__data').prepend($html);
                    }else{
                        $('#js__data').html($html);
                    }
                    
                }else{
                    $('#js__data').append($html);
                }
            }
            return false;
        }
        /**
         * 数据写入状态控制栏
         * @param {bool} runMk 
         */
        progress(runMk){            
            var modal = $('#write_ds');
            var form = modal.find('form');
            var grogs = modal.find('div.progress');
            if(runMk){
                form.addClass('invisible');
                grogs.attr('class', 'progress');
                this._progress(true);
            }else{
                form.removeClass('invisible');
                grogs.attr('class', 'progress invisible');
                this._progress(false);
            }
        }
        /**
         * 状态栏工具 
         * @param {bool} runMk
         */
        _progress(runMk){
            if(runMk){
                var w = 0;
                if(Option.progressId){
                    this._progress(false);
                }
                Option.progressId = setInterval(function(){
                    w = w>100? 0: w;
                    var pBar = $('#write_ds div.progress div.progress-bar');
                    pBar.attr('style', 'width: '+w+'%');
                    pBar.attr('aria-valuenow', w);
                    w += 10;
                }, 500);
            }else if(Option.progressId){
                clearInterval(Option.progressId);
                Option.progressId = false;
            }
        }
        /**
         * @param {bool} runMk 
         */
        floatDsActive(runMk){
            if(runMk){
                if(Option.floatDsTimerId){
                    this._progress(false);
                }
                var instance = this;
                var handerFn = function(){
                    var t = Math.floor(Math.random() * 100);
                    var r = t + Math.floor(Math.random() * 10);
                    $('#float-ds').css({'right': r+'%', 'top':t+'%'});
                    var len = DataStack.length;
                    var rLen = Math.floor(Math.random() * len);
                    var el = DataStack[rLen];
                    instance.objectRenderCard(el);
                };
                Option.floatDsTimerId = setInterval(handerFn, 3000);
                // handerFn();
                $('#float-ds .card').attr('class', 'card bg-secondary text-dark');
            }else if(Option.floatDsTimerId){
                clearInterval(Option.floatDsTimerId);                
            }
            // 聚焦时
            if(!runMk){
                $('#float-ds .card').attr('class', 'card bg-dark text-white');
            }
        }
        /**
         * 对应渲染卡片
         * @param {JSON} obj 
         */
        objectRenderCard(obj){
            if('object' == typeof obj){
                var card = $('#float-ds .card-body');
                card.find('.card-title').html(obj.sign? obj.sign: '匿名');
                card.find('.card-subtitle').html(obj.mtime + (obj.city? ' ('+obj.city+')':''));
                card.find('.card-text').html(obj.content);
            }
        }
    }
    new Pager();
});